package com.hellobike.haxing.modules.wms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.dto.*;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderHeader;
import com.hellobike.haxing.modules.wms.entity.ReturnWarehouseHeader;
import com.hellobike.haxing.modules.wms.entity.ShippingDetail;
import com.hellobike.haxing.modules.wms.entity.ShippingHeader;
import com.hellobike.haxing.modules.wms.enums.DeliveryOrderStatusEnum;
import com.hellobike.haxing.modules.wms.enums.ReturnStatusEnum;
import com.hellobike.haxing.modules.wms.enums.ShippingStatusEnum;
import com.hellobike.haxing.modules.wms.enums.ShippingTypeEnum;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsShippingFacade;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderHeaderService;
import com.hellobike.haxing.modules.wms.service.IReturnWarehouseHeaderService;
import com.hellobike.haxing.modules.wms.service.IShippingDetailService;
import com.hellobike.haxing.modules.wms.service.IShippingHeaderService;
import com.hellobike.haxing.modules.wms.utils.FileUtil;
import com.hellobike.haxing.modules.wms.utils.HtmlToPdf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: t_wms_shipping_header
 * @Author: haxing-boot
 * @Date: 2020-02-02
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wms/shippingHeader")
@Slf4j
public class ShippingHeaderController extends WmsBaseController<ShippingHeader, IShippingHeaderService> {
    @Autowired
    private IShippingHeaderService shippingHeaderService;
    @Autowired
    private IShippingDetailService shippingDetailService;
    @Autowired
    private WmsShippingFacade wmsShippingFacade;
    @Autowired
    private IDeliveryOrderHeaderService deliveryOrderHeaderService;
    @Autowired
    private IReturnWarehouseHeaderService returnWarehouseHeaderService;


    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 分页列表查询
     *
     * @param shippingHeader
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShippingHeader shippingHeader,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        shippingHeader.setWarehouseId(getWarehouseId());
        QueryWrapper<ShippingHeader> queryWrapper = QueryGenerator.initQueryWrapper(shippingHeader, req.getParameterMap());
        Page<ShippingHeader> page = new Page<ShippingHeader>(pageNo, pageSize);
        page.addOrder(OrderItem.desc("id"));
        IPage<ShippingHeader> pageList = shippingHeaderService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody JSONObject param) {
        try {
            ShippingHeader shippingHeader = param.getObject("shippingHeader", ShippingHeader.class);
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.addShipping(shippingHeader, ids, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("添加成功！");
    }

    @AutoLog(value = "t_wms_shipping_header-addReturn", operateType = 2)
    @PostMapping(value = "/addReturn")
    public Result<?> addReturn(@RequestBody JSONObject param) {
        try {
            ShippingHeader shippingHeader = param.getObject("shippingHeader", ShippingHeader.class);
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.addReturnShipping(shippingHeader, ids, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param param
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody JSONObject param) {
        try {
            ShippingHeader shippingHeader = param.getObject("shippingHeader", ShippingHeader.class);
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.updateShipping(shippingHeader, ids, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("编辑成功!");
    }

    @AutoLog(value = "t_wms_shipping_header-editReturn", operateType = 3)
    @PutMapping(value = "/editReturn")
    public Result<?> editReturn(@RequestBody JSONObject param) {
        try {
            ShippingHeader shippingHeader = param.getObject("shippingHeader", ShippingHeader.class);
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.updateReturnShipping(shippingHeader, ids, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) throws WmsServiceException {
        ShippingHeader shippingHeader = shippingHeaderService.getById(id);
        if (shippingHeader == null) {
            throw new WmsServiceException("装车单不存在");
        }
        if (!ShippingStatusEnum.INIT.getValue().equals(shippingHeader.getShippingStatus())) {
            throw new WmsServiceException("非初始化的装车单不能删除");
        }
        List<ShippingDetail> detailList = shippingDetailService.getByHeaderId(shippingHeader.getId());
        if (ShippingTypeEnum.SH.getValue().equals(shippingHeader.getShippingType())) {
            for (ShippingDetail shippingDetail : detailList) {
                DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(shippingDetail.getDeliveryHeaderId());
                orderHeader.setOrderStatus(DeliveryOrderStatusEnum.PICKED.getValue());
                if (!deliveryOrderHeaderService.updateById(orderHeader)) {
                    throw new WmsServiceException("回退订单状态异常");
                }
                if (!shippingDetailService.removeById(shippingDetail.getId())) {
                    throw new WmsServiceException("清除明细异常");
                }
            }
        } else if (ShippingTypeEnum.TH.getValue().equals(shippingHeader.getShippingType())) {
            for (ShippingDetail shippingDetail : detailList) {
                ReturnWarehouseHeader returnWarehouseHeader = returnWarehouseHeaderService.getById(shippingDetail.getDeliveryHeaderId());
                returnWarehouseHeader.setReturnStatus(ReturnStatusEnum.WAIT_RETURN.getValue());
                if (!returnWarehouseHeaderService.updateById(returnWarehouseHeader)) {
                    throw new WmsServiceException("回退退货单状态异常");
                }
                if (!shippingDetailService.removeById(shippingDetail.getId())) {
                    throw new WmsServiceException("清除明细异常");
                }
            }
        }
        shippingHeaderService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shippingHeaderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShippingHeader shippingHeader = shippingHeaderService.getById(id);
        if (shippingHeader == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(shippingHeader);
    }


    @GetMapping(value = "/getDetail")
    public Result<?> getDetail(@RequestParam(name = "id", required = true) Long id) {
        List<ShippingDetail> details = shippingDetailService.getByHeaderId(id);
        if (details == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(details);
    }

    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_shipping_header-导出pdf", operateType = 6)
    @RequestMapping(value = "/download")
    public void download(@RequestParam Long id, HttpServletResponse response) throws WmsServiceException, WmsExportException {
        try {
            String filename = RandomStringUtils.random(12, false, true) + ".pdf";
            String type = new MimetypesFileTypeMap().getContentType(filename);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type", type);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            Context context = new Context();  //thymeleaf包下的
            Map<String, Object> map = new HashMap<>();
            List<ExportShippingShopPdfDto> list = wmsExportFacade.exportShippInfo(id);
            log.info("{}", JSON.toJSONString(list));
            map.put("shopPoList", list);
            context.setVariables(map);
            String html = templateEngine.process("shop_print", context);
            try {
                log.info(html);
                HtmlToPdf.topdf(html, "/tmp/" + filename);
                FileUtil.download("/tmp/" + filename, response);
            } catch (Exception ex) {
                log.error("", ex);
            }
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_shipping_header-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestParam Long id) throws WmsExportException {
        try {
            String title = "";
            List<Map<String, Object>> exportList = new ArrayList<>();
            Map<String, List<ExportShippingDto>> data = wmsExportFacade.exportShipping(id);
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            mv.addObject(NormalExcelConstants.FILE_NAME, title);
            for (Map.Entry<String, List<ExportShippingDto>> entry : data.entrySet()) {
                title = entry.getKey();
                Map<String, Object> map = new HashMap<>();
                map.put(NormalExcelConstants.PARAMS, new ExportParams(title, "导出人:" + getSysUser().getUsername(), title));
                map.put(NormalExcelConstants.CLASS, ExportShippingDto.class);
                map.put(NormalExcelConstants.DATA_LIST, entry.getValue());
                exportList.add(map);
            }
            mv.addObject(NormalExcelConstants.MAP_LIST, exportList);
            return mv;
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_shipping_header-退货导出excel", operateType = 6)
    @RequestMapping(value = "/returnExportXls")
    public ModelAndView returnExportXls(@RequestParam Long id) throws WmsExportException {
        try {
            String title = "";
            Map<String, List<ExportReturnShippingDto>> data = wmsExportFacade.exportReturnShipping(id);
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            mv.addObject(NormalExcelConstants.FILE_NAME, title);
            List<Map<String, Object>> exportList = new ArrayList<>();
            for (Map.Entry<String, List<ExportReturnShippingDto>> entry : data.entrySet()) {
                title = entry.getKey();
                Map<String, Object> map = new HashMap<>();
                map.put(NormalExcelConstants.PARAMS, new ExportParams(title, "导出人:" + getSysUser().getUsername(), title));
                map.put(NormalExcelConstants.CLASS, ExportReturnShippingDto.class);
                map.put(NormalExcelConstants.DATA_LIST, entry.getValue());
                exportList.add(map);
            }
            mv.addObject(NormalExcelConstants.MAP_LIST, exportList);
            return mv;
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }


    @AutoLog(value = "t_wms_shipping_header-导出exportUserInfo", operateType = 6)
    @RequestMapping(value = "/exportUserInfo")
    public ModelAndView exportUserInfo(@RequestParam Long id) throws WmsExportException {
        try {
            String title = "";
            List<Map<String, Object>> exportList = new ArrayList<>();
            Map<String, List<ExportShippingUserInfoDto>> data = wmsExportFacade.exportShippingUserInfo(id);
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            mv.addObject(NormalExcelConstants.FILE_NAME, title);
            for (Map.Entry<String, List<ExportShippingUserInfoDto>> entry : data.entrySet()) {
                title = entry.getKey();
                Map<String, Object> map = new HashMap<>();
                map.put(NormalExcelConstants.PARAMS, new ExportParams(title, "导出人:" + getSysUser().getUsername(), title));
                map.put(NormalExcelConstants.CLASS, ExportShippingUserInfoDto.class);
                map.put(NormalExcelConstants.DATA_LIST, entry.getValue());
                exportList.add(map);
            }
            mv.addObject(NormalExcelConstants.MAP_LIST, exportList);
            return mv;
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "t_wms_shipping_header-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShippingHeader.class);
    }

    @AutoLog(value = "t_wms_shipping_header-confirmSend", operateType = 5)
    @RequestMapping(value = "/confirmSend", method = RequestMethod.POST)
    public Result<?> confirmSend(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.batchStartShipping(ids, getWarehouseId(), getSysUserId());
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("确认发运成功!");
    }

    @AutoLog(value = "t_wms_shipping_header-confirmSendReturn", operateType = 5)
    @RequestMapping(value = "/confirmSendReturn", method = RequestMethod.POST)
    public Result<?> confirmSendReturn(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsShippingFacade.batchStartReturnShipping(ids, getWarehouseId(), getSysUserId());
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("确认发运成功!");
    }
}
